﻿using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Phone.Shell;
using WinSource.ViewModel;

namespace WinSource.Views
{
    public partial class MainPage
    {
        #region Constructor

        public MainPage()
        {
            InitializeComponent();

            Messenger.Default.Register<IsRefreshingArticlesPropertyChangedMessage>(this, action => DispatcherHelper.CheckBeginInvokeOnUI(SetApplicationBarVisibility));
        }

        #endregion

        #region Event Handlers

        private void PhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            SetApplicationBarVisibility();
        }

        private void ApplicationBarStateChanged(object sender, ApplicationBarStateChangedEventArgs e)
        {
            ApplicationBar applicationBar = sender as ApplicationBar;

            if (applicationBar != null)
            {
                applicationBar.Opacity = e.IsMenuVisible ? 1 : .65;
            }
        }

        #endregion

        #region Private Methods

        private void SetApplicationBarVisibility()
        {
            MainViewModel mainViewModel = DataContext as MainViewModel;

            if (mainViewModel != null)
            {
                ApplicationBar.IsVisible = !mainViewModel.IsRefreshingArticles;
            }
        }

        #endregion
    }
}